import breaDcrumb from '@/components/breadcrumb';
import {
  getListByTypeId
} from '@/api/common.js';
import {
  getFirmDetection,
  getNormByDetection
} from '@/api/basicConfig/CPYquality.js';
import {
  saveStationTest,
  getStationTest,
  getStationNormByDetection,
  // saveNormByDetection
} from '@/api/basicConfig/Sitequality.js';
import {
  getContracts
} from "@/api/GHnumber/share.js";
import { getDicType } from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";
import { getcompany, getUserAutList, get_simple_organization } from "@/api/common.js";
import { get_station_list } from "@/api/smart/stocksake.js";
export default {
  components: {
    breaDcrumb
  },
  data() {
    return {
      UserInfo: '',
      contractTypelist: [{
        value: '验收标准',
        id: 0
      },
      {
        value: '检测频率设置',
        id: 1
      }
      ],
      currenindex: 0,
      companyId: '',
      companylist: [],
      showsiteId: '',
      siteId: '',
      siteIdList: [],
      // 左侧导航
      leftList: [{
        text: '原物料',
        value: 1
      }, {
        text: '强度等级',
        value: 2
      }],
      leftIndex: 1,
      showleftIndex: 1,
      // 左侧数据
      leftitemList: [],
      leftitemId: '',
      showleftitemId: '',
      //模块一
      rightIndex: '',
      showrightIndex: '',
      categoryList: [{
        name: '请优先选择对应的原物料或者强度等级'
      }],
      tablenav: [],
      rightitemList: [],
      showrightitemList: [],
      Dialog: false,
      newtablenav: [],
      newrightitemList: [],
      tableLoading: false,
      //模块二
      //合同
      contactId: '',
      contactIdist: [{
        name: 'vgUWKWE OY即时比分',
        id: '846541546465'
      },
      {
        name: '十多个即时比分',
        id: '84634534546465'
      },
      {
        name: '爱人我即时比分 ',
        id: '84654154537565'
      }
      ],
      //类别
      leftId: '',
      leftIdList: [],
      // 频率
      rightId: [],
      rightIdList: [{
        itemName: "车",
        id: "1",
        content: ''
      },
      {
        itemName: "吨",
        id: "2",
        content: ''
      },
      {
        itemName: "方",
        id: "3",
        content: ''
      },
      {
        itemName: "小时",
        id: "4",
        content: ''
      },
      ],
      /*存数据*/
      itema: '',
      itemb: '',
      itemc: '',
      /**判断是否是交工数据*/
      signData: false,
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    if (this.UserInfo.adminStatus == 1) {
      /**通过typeId为公司类型id查询所有公司 */
      getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        this.companylist = res.data;
      });
    } else {
      this.siteIdList = await getUserAutList(true)
    }
  },
  watch: {
    /*验收标准，检测频率切换*/
    currenindex() {
      this.initright()
    },
    /*更改站点*/
    async siteId() {
      if (this.currenindex == 1) {
        let data = new Object();
        data.type = this.leftIndex;
        data.companyId = this.companyId;
        data.rawId = this.leftitemId;
        await this.getContract()
        await getFirmDetection(data).then(res => {
          if (res.data.length == 0 || this.contactIdist.length == 0) {
            this.leftIdList = []
            this.itema = ''
            this.itemb = ''
            this.itemc = []
            this.contactId = ''
            this.leftId = ''
            this.rightId = []
            console.log(123)
          } else {
            this.leftIdList = res.data;
            this.getStation()
          }
        });
      } else {
        this.getTable()
      }
    },
    /*更改公司*/
    async companyId() {
      this.showleftitemId = ''
      this.rightIndex = ''
      this.showrightIndex = ''
      this.categoryList = [{
        name: '暂未绑定检测类别'
      }]
      if (this.currenindex == 0) {
        await this.gettightList()
      }
    },
    /*更改原物料或者强度等级*/
    async leftitemId() {
      if (this.leftitemId == '') {
        return;
      }
      await this.getContract()
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      if (this.currenindex == 1) {
        data.status = 2
        getFirmDetection(data).then(res => {
          if (res.data.length == 0) {
            this.leftIdList = []
          } else {
            this.leftIdList = res.data;
            this.getStation()
          }
        });
      } else {
        this.gettightList()
      }
    },
    /*原物料或者强度改变后重置右侧数据*/
    leftIndex: {
      handler() {
        switch (this.leftIndex) {
          case 1: {
            getDicType({
              code: "MATname"
            }).then((res) => {
              this.leftitemList = res.data.items.map((res) => {
                let obj = {
                  id: res.id,
                  name: res.itemName,
                };
                return obj;
              });
            });
            this.initright()
            return;
          }
          case 2: {
            getListByTypeId({
              typeId: 1
            }).then(res => {
              this.leftitemList = res.data;
              this.initright()
            });
            return;
          }
        }
      },
      deep: false, //是否深度监听，true为是，默认为false
      immediate: true //immediate表示在watch中首次绑定的时候，是否执
    },
    /*右侧检测类别*/
    rightIndex() {
      this.getTable()
    },
  },
  methods: {
    /**通过站点查询公司 */
    get_simple_organizationFun(id) {
      get_simple_organization({ id: id }).then((res) => {
        this.companyId = res.data?.id || ''
        this.company = res.data?.name || ''
      });//查询站点所属公司
    },
    /*根据公司获取站点*/
    setstationIdlist() {
      get_station_list({ parentId: this.companyId }).then((res) => {
        this.siteIdList = res.data;
        this.siteId = ''
        this.showsiteId = ''
        if (this.siteIdList.length > 0) {
          this.siteId = this.siteIdList[0].id
          this.showsiteId = this.siteIdList[0].id
        }
      });
    },
    async getContract() {
      if (this.siteId && this.leftitemId) {
        let data = {
          id: this.leftitemId,
          stations: this.siteId,
        };
        await getContracts(data).then((res) => {
          this.contactIdist = res.data;
          this.contactIdist.splice(0, 0, { contractNo: '通用设置', contractId: '1' })
        });
      } else {
        this.contactIdist = []
        this.contactIdist.splice(0, 0, { contractNo: '通用设置', contractId: '1' })
      }
    },
    /*获取检测类别*/
    gettightList() {
      let _this = this
      let data = new Object();
      data.type = _this.leftIndex;
      data.companyId = _this.companyId;
      if (_this.leftIndex == 1) {
        data.rawId = _this.leftitemId;
      } else {
        data.strengthGradeId = _this.leftitemId;
      }
      console.log(11);
      getFirmDetection(data).then(res => {
        console.log(res);
        if (res.data.length == 0) {
          _this.rightIndex = ''
          _this.showrightIndex = ''
          _this.categoryList = [{
            name: '暂未绑定检测类别'
          }]
        } else {
          _this.categoryList = res.data;
          _this.rightIndex = res.data[0].id
          _this.showrightIndex = res.data[0].id
        }
      });
    },
    /*获取表数据*/
    getTable() {
      if (this.companyId == '' || this.siteId == '' || this.leftitemId == '') {
        return
      }
      this.tableLoading = true
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      data.stationId = this.siteId;
      data.id = this.rightIndex
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      getStationNormByDetection(data).then(res => {
        this.tableLoading = false
        this.tablenav = res.data?.claim || []
        this.rightitemList = this.copy(res.data?.list || [])
        this.showrightitemList = this.copy(res.data?.list || [])
        this.tablenav.unshift({
          name: "检测类别"
        })

      })
    },
    /*获取公司标准*/
    getnewtable() {
      if (this.companyId == '' || this.siteId == '' || this.leftitemId == '') {
        this.$message({
          showClose: true,
          message: '警告哦，请选择对应的数据后再获取公司标准',
          type: 'warning'
        });
        return
      }
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      data.id = this.rightIndex
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      getNormByDetection(data).then(res => {
        this.newtablenav = res.data.claim
        this.newrightitemList = this.copy(res.data.list)
        this.newtablenav.unshift({
          name: "检测类别"
        })
        let name = this.categoryList.find(res => (res.id == this.rightIndex))?.name
        if (name == '交工数据标准') {
          this.signData = true
        } else {
          this.signData = false
        }
        this.Dialog = true
      })
    },
    /*拷贝*/
    copy(list) {
      let str = JSON.stringify(list)
      return JSON.parse(str)
    },
    addnbd() {
      let _this = this
      /*构造数据对象*/
      let station = _this.siteIdList.find(res => (res.id == _this.siteId)).name
      function setdata(parameterSettingId, content) {
        this.type = _this.leftIndex;
        this.companyId = _this.companyId;
        this.stationId = _this.siteId;
        this.parameterSettingId = parameterSettingId;
        this.content = content;
        if (_this.leftIndex == 1) {
          this.rawId = _this.leftitemId;
        } else {
          this.strengthGradeId = _this.leftitemId;
        }
      }
      let arr = []
      this.rightitemList.forEach(res => {
        console.log(res)
        for (let key in res) {
          if (key !== '0') {
            arr.push(new setdata(res[key]?.id, res[key]?.name))
          }
        }
      })
      for (let key in arr) {
        if (arr[key]?.content == '') {
          this.$message({
            message: '请选择要操作的数据项',
            type: 'warning'
          });
          return;
        }
      }
      this.$router.push({ name: "sign_Sitequality", query: { tablenav: JSON.stringify(this.tablenav), rightitemList: JSON.stringify(this.rightitemList), arr: JSON.stringify(arr), company: this.company, station: station, type: 1 } });
      console.log(this.tablenav)
      console.log(arr)
      console.log(this.rightitemList)
      console.log(this.company)
      console.log(station)
      // saveNormByDetection(arr).then(() => {
      //   _this.getTable()
      // })
    },
    initright() {
      this.rightIndex = ''
      this.showrightIndex = ''
      this.categoryList = [{
        name: '请优先选择对应的原物料或者强度等级'
      }]
      this.tablenav = []
      this.rightitemList = []
      this.showrightitemList = []
      this.contactIdist = []
      this.leftIdList = []
      this.showleftitemId = ''
      this.leftitemId = ''
      this.contactId = ''
      this.leftId = ''
      this.rightId = []
      this.itema = ''
      this.itemb = ''
      this.itemc = []
    },
    /*验收频率切换*/
    choose(num) {
      this.currenindex = num
    },
    change(hid, show, value) {
      let _this = this;
      if (_this.currenindex == 1) {
        if (_this.contactId !== _this.itema || _this.leftId !== _this.itemb || _this.rightId.length != _this.itemc.length) {
          _this.$confirm('请保存更改数据,否则数据将会丢失?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'bottom_all_two',
            confirmButtonClass: 'bottom_all',
            type: 'warning'
          }).then(() => {
            _this[show] = _this[hid]
            _this.saveStation();

          }).catch(() => {
            _this[show] = value;
            _this[hid] = value;
          });
          return;
        }
        _this[show] = value;
        _this[hid] = value;
      } else {
        if (JSON.stringify(_this.showrightitemList) !== JSON.stringify(_this.rightitemList)) {
          _this.$confirm('请保存更改数据,否则数据将会丢失?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'bottom_all_two',
            confirmButtonClass: 'bottom_all',
            type: 'warning'
          })
            .then(() => {
              _this[show] = _this[hid]
              _this.addnbd();

            })
            .catch(() => {
              _this[show] = value;
              _this[hid] = value;
            });
          return;
        }
        _this[show] = value;
        _this[hid] = value;
      }

    },
    /*频率获取对应的绑定数据*/
    getStation() {
      this.$data.rightIdList = this.$options.data().rightIdList
      let _this = this
      if (_this.siteId == '' || _this.companyId == '' || _this.leftitemId == '') {
        return
      }
      let data = new Object()
      data.materialsType = _this.leftIndex;
      data.stationId = _this.siteId;
      data.companyId = _this.companyId;
      data.materialsId = _this.leftitemId;
      getStationTest(data).then(res => {
        if (res.data.length > 0) {
          _this.itema = res.data[0].contractId
          _this.itemb = res.data[0].qualityDetectionId
          _this.itemc = res.data.map(res => (res.frequencyId))
          _this.contactId = res.data[0].contractId
          _this.leftId = res.data[0].qualityDetectionId
          _this.rightId = res.data.map(res => (res.frequencyId))
          res.data.forEach((v) => {
            _this.rightIdList.forEach((v2) => {
              if (v2.id == v.frequencyId) {
                v2.content = v.content
              }
            })
          })
        } else {
          _this.itema = ''
          _this.itemb = ''
          _this.itemc = []
          _this.contactId = ''
          _this.leftId = ''
          _this.rightId = []
        }
      })
    },
    /*保存频率*/
    saveStation() {
      let _this = this
      console.log(_this.rightId);
      if (_this.contactId == '' || _this.leftId == '' || _this.rightId == []) {
        this.$message({
          message: '警告哦，请选择完整数据',
          type: 'warning'
        });
        return
      }

      function setdata(a, b, c) {
        this.materialsType = _this.leftIndex;
        this.stationId = _this.siteId;
        this.companyId = _this.companyId;
        this.materialsId = _this.leftitemId;
        this.qualityDetectionId = b
        this.contractId = a
        this.frequencyId = c;
        this.frequency = _this.rightIdList.find(res => (res.id == c)).itemName;
        this.content = _this.rightIdList.find(res => (res.id == c)).content;
      }
      let arr = []
      _this.rightId.forEach((v) => {
        arr.push(new setdata(_this.contactId, _this.leftId, v))
      })
      saveStationTest(arr).then(() => {
        _this.getStation()
      })
    }
  },


};